package com.xb.service.imp;

import com.xb.entity.*;
import com.xb.mapper.*;
import com.xb.service.ITollTakeDrugService;
import com.xb.util.Result;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * entityService业务层处理
 */
@Service
public class TollTakeDrugServiceImp implements ITollTakeDrugService {
    @Resource
    private TollTakeDrugMapper tollTakeDrugMapper;
    @Resource
    private GetMedicalRecordMapper recordMapper;
    @Resource
    private MedicalRecordMapper medicalRecordMapper;
    @Resource
    private DrugMapper drugMapper;
    @Resource
    private GooutMapper gooutMapper;
    @Resource
    private UserMapper userMapper;

    @Override
    public Result getMedicalRecord(String prescriptionNum) {
        Result result = new Result();
        try {
            GetMedicalRecord medicalRecordByPrescriptionNum = recordMapper.getMedicalRecordByPrescriptionNum(prescriptionNum);
            if (medicalRecordByPrescriptionNum.getChargeStatus() == 1) {
                if (medicalRecordByPrescriptionNum.getDrugStatus() == 0) {
                    medicalRecordByPrescriptionNum.setExaminationCost(recordMapper.getExaminationCostByPrescriptionNum(prescriptionNum));
                    medicalRecordByPrescriptionNum.setNowDate(new Date());
                    result.setData(medicalRecordByPrescriptionNum);
                    result.setStatus(Result.RESPONSE_SUCCESS);
                } else {
                    result.setMessage("该处方单已取药！");
                }

            } else {
                result.setMessage("该处方单未交费！");
            }
            return result;
        } catch (NullPointerException e) {
            e.printStackTrace();
            result.setMessage("未查到该处方单的信息！");
            return result;
        }
    }

    @Transactional
    @Override
    public Result saveTakingDrugInfo(String prescriptionNum, HttpSession session) {
        Result result = new Result();
        try {
            MedicalRecord medicalRecord = medicalRecordMapper.selectMedicalRecordByPrescriptionNum(prescriptionNum);
            TollTakeDrug tollTakeDrug = tollTakeDrugMapper.selectTollTakeDrugByPrescriptionNum(prescriptionNum);
            String email = (String) session.getAttribute("email");
            User user = userMapper.selectUserByEmail(email);

            // 修改TollTakeDrug
            // 获取当前时间
            Date currentTime = new Date();
            // 创建SimpleDateFormat对象，定义时间格式
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            tollTakeDrug.setTakingDrugDateTime(sdf.format(currentTime));
            tollTakeDrug.setTakingDrugOperator(user.getUsername());
            tollTakeDrug.setTakingDrugStatus(1);
            if(tollTakeDrugMapper.updateTollTakeDrug(tollTakeDrug) == 0){
                throw new IllegalAccessException("tollTake更新失败");
            }

            String drugIds = medicalRecord.getDrugIds();
            String[] dataArray = drugIds.split(",");
            Map<Integer, Integer> map = new HashMap<>();
            for (String element : dataArray) {
                int key = Integer.parseInt(element);
                map.put(key, map.getOrDefault(key, 0) + 1);
            }
            // 修改Drug部分代码
            Drug drug;
            for (int key : map.keySet()) {
                drug = drugMapper.selectDrugById(key);
                if (drug.getDrugCount() < map.get(key) || drug.getDrugCount() < 0) {
                    throw new IllegalAccessException(drug.getName() + "库存不足");
                }
                drug.setDrugCount(drug.getDrugCount() - map.get(key));
                if (drugMapper.updateDrug(drug) == 0) {
                    throw new IllegalAccessException("drug更新失败");
                }
            }

            // 修改Goout代码
            Goout goout;
            Set<Map.Entry<Integer, Integer>> entrySet = map.entrySet();
            for (Map.Entry<Integer, Integer> entry : entrySet) {
                goout = new Goout();
                drug = drugMapper.selectDrugById(entry.getKey());
                goout.setDrugId(entry.getKey());
                goout.setDrugName(drug.getName());
                goout.setDrugNum(entry.getValue());
                goout.setMoney(drug.getPrice() * entry.getValue() + " 元");
                goout.setTolltakedrugNo(prescriptionNum);
                goout.setPatientId(String.valueOf(tollTakeDrug.getPatientId()));
                goout.setCreateTime(new Date());
                if (gooutMapper.insertGoout(goout) == 0) {
                    throw new IllegalAccessException("goout更新失败");
                }
            }
            result.setStatus(Result.RESPONSE_SUCCESS);
            return result;

        } catch (IllegalAccessException e) {
            result.setStatus(Result.RESPONSE_FAIL);
            result.setMessage(e.getMessage());
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return result;
        } catch (Exception e) {
            result.setStatus(Result.RESPONSE_EXCEPTION);
            result.setMessage("系统出现故障！请联系管理员");
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return result;
        }
    }
}
